<template>
  <div>
    <!-- 课件预览 -->
    <h2>
      {{ $route.query.name }}——第{{ $route.query.sort }}课时
      <el-button
        class="u-h2-btn"
        type="primary"
        v-if="!isSave"
        @click="isSave = !isSave"
        >编辑</el-button
      >
      <el-button class="u-h2-btn" type="primary" v-else @click="isSaveFn()"
        >保存</el-button
      >
    </h2>
    <div class="z-clear"></div>
    <el-row>
      <el-col :span="12">
        <div class="u-from-box">
          <el-form ref="form" :model="form" label-width="150px">
            <el-form-item label="课时名称">
              <el-input v-model="form.name" :disabled="!isSave"></el-input>
            </el-form-item>
            <el-form-item label="课时简介">
              <el-input
                type="textarea"
                v-model="form.description"
                :disabled="!isSave"
              ></el-input>
            </el-form-item>
            <el-form-item label="主讲课件">
              <div class="u-no-obj" v-if="!form.course_ware_name">
                <i class="el-icon-folder-opened"></i>
              </div>
              <div class="u-class-info" v-if="form.course_ware_name">
                <div>
                  <el-image
                    v-if="setImgType(form.course_ware_name) == 'img'"
                    class="u-img-video"
                    :src="form.course_ware_link"
                    :preview-src-list="[form.course_ware_link]"
                    fit="cover"
                  ></el-image>
                  <video
                    class="u-img-video"
                    v-if="setImgType(form.course_ware_name) == 'video'"
                    :src="item[1]"
                    controls="controls"
                  ></video>
                </div>
                <div class="u-class-info-down">
                  <span>
                    <a
                      class="u-obj-name"
                      @click="openUrl(form.course_ware_link)"
                      >{{ form.course_ware_name }}</a
                    >
                  </span>
                  <span>
                    <!-- <i class="el-icon-download"></i> -->
                    <i
                      @click="deleteObj(undefined, 'teacher')"
                      v-if="form.course_ware_name && isSave"
                      class="el-icon-delete"
                    ></i>
                  </span>
                </div>
              </div>
            </el-form-item>
            <el-form-item label>
              <el-upload
                action
                multiple
                :limit="1"
                :http-request="uploadImg"
                ref="uploadZip"
                :on-exceed="handleExceed_1"
              >
                <el-button class="u-mar-bottom" type="primary" v-if="isSave"
                  >上传课件 +</el-button
                >
              </el-upload>
            </el-form-item>
            <!-- 学生课件 -->
            <el-form-item label="学生课件">
              <div class="u-no-obj" v-if="!form.student_links_name">
                <i class="el-icon-folder-opened"></i>
              </div>
              <div class="u-class-info" v-if="form.student_links_name">
                <div>
                  <el-image
                    v-if="setImgType(form.student_links_name) == 'img'"
                    class="u-img-video"
                    :src="form.student_course_ware_link"
                    :preview-src-list="[form.student_course_ware_link]"
                    fit="cover"
                  ></el-image>
                  <video
                    class="u-img-video"
                    v-if="setImgType(form.student_links_name) == 'video'"
                    :src="item[1]"
                    controls="controls"
                  ></video>
                </div>
                <div class="u-class-info-down">
                  <span>
                    <a
                      class="u-obj-name"
                      @click="openUrl(form.student_course_ware_link)"
                      >{{ form.student_links_name }}</a
                    >
                  </span>
                  <span>
                    <i
                      @click="deleteObj(undefined, 'student')"
                      v-if="form.student_links_name && isSave"
                      class="el-icon-delete"
                    ></i>
                  </span>
                </div>
              </div>
            </el-form-item>
            <el-form-item label>
              <el-upload
                action
                multiple
                :limit="1"
                :http-request="uploadImg_student"
                ref="uploadZip_student"
                :on-exceed="handleExceed_1"
              >
                <el-button class="u-mar-bottom" type="primary" v-if="isSave"
                  >上传学生课件 +</el-button
                >
              </el-upload>
            </el-form-item>

            <el-form-item label="素材">
              <div
                class="u-no-obj"
                v-if="form.material_info && form.material_info.length < 1"
              >
                <i class="el-icon-folder-opened"></i>
              </div>
              <div class="m-material-box">
                <div
                  class="m-video-box"
                  v-for="(item, index) in form.material_info"
                  :key="index"
                >
                  <div>
                    <el-image
                      class="u-img-video"
                      v-if="setImgType(item[0]) == 'img'"
                      :src="item[1]"
                      :preview-src-list="[item[1]]"
                      fit="cover"
                    ></el-image>
                    <video
                      class="u-img-video"
                      v-if="setImgType(item[0]) == 'video'"
                      :src="item[1]"
                      controls="controls"
                    ></video>
                  </div>
                  <div class="u-video-info">
                    <span>
                      <a
                        download="下载素材"
                        @click="downLoad(item[1])"
                        target="_blank"
                      >
                        {{ item[0] }}
                        <i class="el-icon-download"></i>
                      </a>
                    </span>

                    <span>
                      <!-- <i class="el-icon-download"></i> -->
                      <i
                        @click="deleteObj(index)"
                        v-if="isSave"
                        class="el-icon-delete"
                      ></i>
                    </span>
                  </div>
                </div>
              </div>
              <el-progress
                :percentage="percentage"
                v-show="showRentPrise"
              ></el-progress>
            </el-form-item>
            <el-form-item label>
              <el-upload
                action
                multiple
                :limit="30"
                :on-change="handlePreview"
                ref="uploadArr"
                :http-request="uploadImgArr"
                :on-exceed="handleExceed_10"
              >
                <!-- :file-list="fileList" -->
                <el-button
                  type="primary"
                  @click="arrWarning = true"
                  v-if="isSave"
                  >上传素材 +</el-button
                >
              </el-upload>
            </el-form-item>
          </el-form>
          <el-collapse v-model="activeNames">
            <el-collapse-item
              v-for="(item, indexs) in questionList"
              :key="indexs"
              :title="item.label + '(' + '共' + item.data.length + '题' + ')'"
              v-show="item.data && item.data.length"
              :name="indexs"
            >
              <ul>
                <li v-for="(ele, $index) in item.data">
                  <Q :index="$index" :item="ele"></Q>
                </li>
              </ul>
            </el-collapse-item>
          </el-collapse>
        </div>
        <!-- <div class="u-exercises-box">
          <el-form ref="form" :model="form" label-width="80px">
            <el-form-item label="预习题"></el-form-item>
          </el-form>
        </div>-->
      </el-col>
    </el-row>
  </div>
</template>
<script>
import { ossUploadZip } from '@/api/api.js'
import { ossUploadFile } from '@/api/mixins'
import F from '@/utils/f'
import {
  queryAutoSqlOne,
  lessonUpdate,
  updateWithoutCourseWareId,
  getWorkId,
  getListQuestionsByVolumeId
} from '@/api/course.js'
import Q from './list'
export default {
  data () {
    return {
      arrWarning: true,
      isSave: false,
      showRentPrise: false,
      percentage: 0,
      activeNames: '',
      questionList: [
        {
          label: '预习作业',
          data: []
        },
        {
          label: '课堂练',
          data: []
        },
        {
          label: '出门测',
          data: []
        },
        {
          label: '课后作业',
          data: []
        }
      ],
      form: {
        name: '',
        description: '',
        course_ware_name: null,
        course_ware_link: null,
        material_info: [],
        course_ware_id: '',
        student_links_name: null,
        student_course_ware_link: null
      }
    }
  },
  components: { Q },
  activated () {
    this.getClassHourDetails()
    this.getWorkId()
    // this.getListQuestionsByVolumeId();
  },
  methods: {
    async isSaveFn () {
      let arr = []
      this.form.material_info.map(item => {
        if (arr.length < 30) {
          arr.push({
            name: item[0],
            path: item[1],
            lesson_merterial: [
              {
                course_id: this.$route.query.courseId,
                course_lesson_id: this.$route.query.id
              }
            ]
          })
        }
      })

      if (this.form.course_ware_id) {
        let res = await lessonUpdate({
          'nice_course_ware.name': this.form.course_ware_name,
          'nice_course_ware.links': this.form.course_ware_link,
          'nice_course_ware.student_links_name': this.form.student_links_name,
          'nice_course_ware.student_links': this.form.student_course_ware_link,
          'nice_course_ware.id': this.form.course_ware_id,
          'nice_course_lesson.name': this.form.name,
          'nice_course_lesson.description': this.form.description,
          'nice_course_lesson.id': this.$route.query.id,
          'vo.list': arr
        })
        if (res[0]) {
          return
        }
      } else {
        let res = await updateWithoutCourseWareId({
          'nice_course_ware.name': this.form.course_ware_name,
          'nice_course_ware.links': this.form.course_ware_link,
          'nice_course_ware.student_links_name': this.form.student_links_name,
          'nice_course_ware.student_links': this.form.student_course_ware_link,
          'nice_course_lesson.name': this.form.name,
          'nice_course_lesson.description': this.form.description,
          'nice_course_lesson.id': this.$route.query.id,
          'vo.list': arr
        })
        if (res[0]) {
          return
        }
      }
      this.getClassHourDetails()
      if (this.form.material_info.length > 30) {
        this.$message.warning(
          `您当前累计上传的素材已超出30，超出部分将无法保存`
        )
      }
      setTimeout(() => {
        this.$message({
          message: '保存成功',
          type: 'success'
        })
      }, 2000)

      this.isSave = false
    },

    progress (percentage, checkpoint, res) {
      this.percentage = parseInt(percentage * 100)
    },
    downLoad (e) {
      const downloadFileA = document.createElement('a')
      document.body.append(downloadFileA)
      downloadFileA.href = e
      downloadFileA.download = '下载素材'
      downloadFileA.target = '_blank'
      downloadFileA.rel = 'noopener noreferrer'
      downloadFileA.click()
      document.body.removeChild(downloadFileA)
      //   this.$http({
      //     method: 'get',
      //     url: e,
      // // 必须显式指明响应类型是一个Blob对象，这样生成二进制的数据，才能通过window.URL.createObjectURL进行创建成功
      //     responseType: 'blob'
      //   }).then((res) => {
      //     if (!res) {
      //       return
      //     }
      // // 将lob对象转换为域名结合式的url
      //     let blobUrl = window.URL.createObjectURL(res.data)
      //     let link = document.createElement('a')
      //     document.body.appendChild(link)
      //     link.style.display = 'none'
      //     link.href = blobUrl
      // // 设置a标签的下载属性，设置文件名及格式，后缀名最好让后端在数据格式中返回
      //     link.download = '下载素材'
      // // 自触发click事件
      //     link.click()
      //     document.body.removeChild(link)
      //     window.URL.revokeObjectURL(blobUrl)
      //   })
      // window.open(e)
    },

    openUrl (e) {
      window.open(e)
    },
    // 删除素材或者课件
    deleteObj (index, type) {
      if (index === undefined) {
        this.$confirm('此操作将该课件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            if (type == 'teacher') {
              this.form.course_ware_link = null
              this.form.course_ware_name = null
            } else {
              this.form.student_course_ware_link = null
              this.form.student_links_name = null
            }
          })
          .catch(() => {})
      } else {
        this.$confirm('此操作将删除该素材, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.form.material_info.splice(index, 1)
          })
          .catch(() => {})
      }
      // if(){}
    },
    // 上传学生课件
    async uploadImg_student (e) {
      let formData = new FormData()
      formData.append('file', e.file)
      let res = await ossUploadZip(formData)
      if (res[0]) {
        return
      }
      // 赋值
      this.form.student_course_ware_link = res[1].data
      this.form.student_links_name = e.file.name
      this.$ref.uploadZip_student.clearFiles()
    },
    // 上传课件
    async uploadImg (e) {
      let formData = new FormData()
      formData.append('file', e.file)
      let res = await ossUploadZip(formData)
      if (res[0]) {
        return
      }
      this.form.course_ware_link = res[1].data
      this.form.course_ware_name = e.file.name
      this.$ref.uploadZip.clearFiles()

      // let res2 = await courseWareupload({
      //   'nice_course_ware.name': e.file.name,
      //   'nice_course_ware.links': url,
      //   'nice_course_lesson.id': this.uploadId
      // })
      // if (res2[0]) {
      //   return
      // }
      // this.getCourseLessonList()
    },
    // 上传素材
    async uploadImgArr (e) {
      let formData = new FormData()
      formData.append('file', e.file)
      ossUploadFile(this, e, 'MATERIAL_RESOURCE').then(res => {
        this.form.material_info.push([e.file.name, res])
      })
      // if (this.form.material_info.length < 11) {
      // if (this.form.material_info.length === 30 && this.arrWarning) {
      //   this.$message.warning(`您当前选择的素材超出30，超出部分将无法保存`)
      //   this.arrWarning = false
      //   this.$ref.uploadArr.clearFiles()
      //   return
      // }

      this.$ref.uploadArr.clearFiles()
    },

    handlePreview (file, fileList) {
      this.fileListLength = fileList.length
    },
    handleExceed_10 (files, fileList) {
      this.$message.warning(
        `当前限制批量选择 30 个文件，本次选择了 ${files.length} 个文件`
      )
    },
    handleExceed_1 (files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${files.length} 个文件`
      )
    },
    setImgType (e) {
      if (!e) {
        return
      }
      if (
        e.indexOf('.npg') !== -1 ||
        e.indexOf('.gif') !== -1 ||
        e.indexOf('.jpg') !== -1
      ) {
        return 'img'
      } else if (e.indexOf('.mp4') !== -1) {
        return 'video'
      }
    },
    async getWorkId () {
      this.questionList = [
        {
          label: '预习作业',
          data: []
        },
        {
          label: '课堂练',
          data: []
        },
        {
          label: '出门测',
          data: []
        },
        {
          label: '课后作业',
          data: []
        }
      ]
      let res = await getWorkId({
        'nice_course_lesson_and_question.course_lesson_id': this.$route.query.id
      })
      if (res[0]) {
        return
      }
      if (res[1].code === 0) {
        let response = res[1].data
        response &&
          response.course_after_volume_id &&
          this.getListQuestionsByVolumeId(
            response.course_after_volume_id,
            'after'
          )
        response &&
          response.course_before_volume_id &&
          this.getListQuestionsByVolumeId(
            response.course_before_volume_id,
            'before'
          )
        response &&
          response.course_current_volume_id &&
          this.getListQuestionsByVolumeId(
            response.course_current_volume_id,
            'current'
          )
        response &&
          response.outdoor_test_volume_id &&
          this.getListQuestionsByVolumeId(
            response.outdoor_test_volume_id,
            'outdoor'
          )
      }
    },
    async getListQuestionsByVolumeId (id, type) {
      let res = await getListQuestionsByVolumeId({
        volume_id: id
      })
      if (res[0]) {
        return
      }
      if (res[1].code === 0) {
        let _obj = {
          homework_id: 133,
          homework_state_id: 1,
          user_id: '1'
        }
        let data = F.returnData(res[1].questionList, true, _obj)
        if (type == 'after') {
          this.questionList[3].data = data
        } else if (type == 'before') {
          this.questionList[0].data = data
        } else if (type == 'current') {
          this.questionList[1].data = data
        } else {
          this.questionList[2].data = data
        }
      }
    },
    async getClassHourDetails () {
      this.isSave = false
      let res = await queryAutoSqlOne({
        table_name: 'nice_course_lesson',
        id: this.$route.query.id
      })
      if (res[0]) {
        return
      }
      this.form.name = res[1].data.name
      this.form.description = res[1].data.description
      this.form.course_ware_name = res[1].data.course_ware_name
      this.form.course_ware_link = res[1].data.course_ware_link
      this.form.course_ware_id = res[1].data.course_ware_id
      this.form.student_course_ware_link = res[1].data.student_course_ware_link
      this.form.student_links_name = res[1].data.student_links_name
      if (res[1].data.material_info) {
        let arr = res[1].data.material_info.split('§')
        let setArr = []
        arr.map(item => {
          setArr.push(item.split('£'))
        })
        this.form.material_info = setArr
      } else {
        this.form.material_info = []
      }
    },
    onSubmit () {
      console.log('submit!')
    }
  }
}
</script>
<style scoped>
.el-collapse {
  margin-left: 80px;
}
h2 {
  text-align: left;
  padding-left: 77px;
}
ul {
  margin: 0px;
  padding: 0px;
  list-style: none;
}
.u-h2-btn {
  float: right;
  margin: 20px 10px 10px 10px;
}
.z-clear {
  clear: both;
}
.u-img-video {
  width: 320px;
  height: 200px;
  margin-bottom: 10px;
}
.u-no-obj {
  width: 320px;
  height: 200px;
  font-size: 35px;
  background: #f5f7fa;
  text-align: center;
  justify-content: center;
  align-items: Center;
  display: flex;
}
.u-class-info {
  display: flex;
}
.u-class-info-down {
  justify-content: center;
  align-items: Center;
  display: flex;
}
.u-class-info i {
  font-size: 18px;
  margin-left: 10px;
}
.m-video-box {
  display: flex;
}
.u-video-info {
  justify-content: center;
  align-items: Center;
  display: flex;
  /* margin-inline-start: 20px; */
}
.u-video-info i {
  font-size: 18px;
  margin-left: 10px;
}
.m-material-box {
  /* margin-top: 10px; */
}
.u-exercises-box {
  margin-top: 30px;
}
.u-from-box {
  /* min-height: 500px; */
}
.u-obj-name {
  margin-left: 20px;
}
.u-mar-bottom {
  margin-bottom: 30px;
}
.el-icon-delete {
  font-size: 14px !important;
  cursor: pointer;
}
.u-from-box >>> .el-upload-list {
  display: none;
}
.el-icon-download {
  float: right;
  margin-top: 12px;
}
</style>
